<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="文章ID" prop="articleId">
        <el-input
          v-model="queryParams.articleId"
          placeholder="请输入文章ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="待处理" value="pending" />
          <el-option label="运行中" value="running" />
          <el-option label="已暂停" value="paused" />
          <el-option label="已完成" value="completed" />
          <el-option label="失败" value="failed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
      </el-form-item>
      <el-form-item label="当前步骤" prop="currentStep">
        <el-select v-model="queryParams.currentStep" placeholder="请选择步骤" clearable>
          <el-option label="文本清理" value="text_clean" />
          <el-option label="AI处理" value="ai_process" />
          <el-option label="中文TTS" value="tts_generate_cn" />
          <el-option label="英文TTS" value="tts_generate_en" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tzai:task:queue:add']"
        >新建任务</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tzai:task:queue:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务ID" align="center" prop="taskId" width="80" />
      <el-table-column label="文章ID" align="center" prop="articleId" width="80" />
      <el-table-column label="任务类型" align="center" prop="taskType" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.taskType === 'full_process'" type="success" size="small">全文处理</el-tag>
          <el-tag v-else-if="scope.row.taskType === 'summary_process'" type="primary" size="small">摘要处理</el-tag>
          <el-tag v-else size="small">{{ scope.row.taskType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 'pending'" type="info">待处理</el-tag>
          <el-tag v-else-if="scope.row.status === 'running'" type="primary">运行中</el-tag>
          <el-tag v-else-if="scope.row.status === 'paused'" type="warning">已暂停</el-tag>
          <el-tag v-else-if="scope.row.status === 'completed'" type="success">已完成</el-tag>
          <el-tag v-else-if="scope.row.status === 'failed'" type="danger">失败</el-tag>
          <el-tag v-else type="info">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="当前步骤" align="center" prop="currentStep" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.currentStep === 'text_clean'">文本清理</span>
          <span v-else-if="scope.row.currentStep === 'ai_process'">AI处理</span>
          <span v-else-if="scope.row.currentStep === 'tts_generate_cn'">中文TTS</span>
          <span v-else-if="scope.row.currentStep === 'tts_generate_en'">英文TTS</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="总进度" align="center" prop="totalProgress" width="150">
        <template slot-scope="scope">
          <el-progress :percentage="scope.row.totalProgress" :color="customColors"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority" width="80" />
      <el-table-column label="重试次数" align="center" prop="retryCount" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.retryCount }} / {{ scope.row.maxRetry }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工作线程" align="center" prop="workerThread" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="错误信息" align="center" prop="errorMessage" width="200" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['tzai:task:queue:query']"
          >详情</el-button>
          <el-button
            v-if="scope.row.status === 'pending'"
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleStart(scope.row)"
            v-hasPermi="['tzai:task:queue:edit']"
          >启动</el-button>
          <el-button
            v-if="scope.row.status === 'running'"
            size="mini"
            type="text"
            icon="el-icon-video-pause"
            @click="handlePause(scope.row)"
            v-hasPermi="['tzai:task:queue:edit']"
          >暂停</el-button>
          <el-button
            v-if="scope.row.status === 'paused'"
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleResume(scope.row)"
            v-hasPermi="['tzai:task:queue:edit']"
          >继续</el-button>
          <el-button
            v-if="scope.row.status === 'failed'"
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleRetry(scope.row)"
            v-hasPermi="['tzai:task:queue:edit']"
          >重试</el-button>
          <el-button
            v-if="['pending', 'running', 'paused'].includes(scope.row.status)"
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleCancel(scope.row)"
            v-hasPermi="['tzai:task:queue:edit']"
          >取消</el-button>
          <el-button
            v-if="['completed', 'failed', 'cancelled'].includes(scope.row.status)"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tzai:task:queue:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="文章ID" prop="articleId">
          <el-input v-model="form.articleId" placeholder="请输入文章ID" type="number" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="form.priority" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="AI模型" prop="aiModelIds">
          <el-select v-model="form.aiModelIds" multiple placeholder="请选择AI模型（空=所有启用）">
            <el-option label="通义千问" :value="1" />
            <el-option label="DeepSeek" :value="2" />
            <el-option label="GPT-4" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="AI并行度" prop="aiParallelLevel">
          <el-input-number v-model="form.aiParallelLevel" :min="1" :max="10" />
        </el-form-item>
        <el-form-item label="TTS引擎" prop="ttsEngineId">
          <el-select v-model="form.ttsEngineId" placeholder="请选择TTS引擎">
            <el-option label="阿里云TTS" :value="1" />
            <el-option label="Azure TTS" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="TTS并行度" prop="ttsParallelLevel">
          <el-input-number v-model="form.ttsParallelLevel" :min="1" :max="10" />
        </el-form-item>
        <el-form-item label="中文音色" prop="cnVoice">
          <el-input v-model="form.cnVoice" placeholder="例如: xiaoyun" />
        </el-form-item>
        <el-form-item label="英文音色" prop="enVoice">
          <el-input v-model="form.enVoice" placeholder="例如: jenny" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 任务详情对话框 -->
    <el-dialog title="任务详情" :visible.sync="detailOpen" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="任务ID">{{ detailData.taskId }}</el-descriptions-item>
        <el-descriptions-item label="文章ID">{{ detailData.articleId }}</el-descriptions-item>
        <el-descriptions-item label="任务类型">
          <el-tag v-if="detailData.taskType === 'full_process'" type="success" size="small">全文处理</el-tag>
          <el-tag v-else-if="detailData.taskType === 'summary_process'" type="primary" size="small">摘要处理</el-tag>
          <el-tag v-else size="small">{{ detailData.taskType }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理模式">
          <el-tag v-if="getProcessMode(detailData) === 'full'" type="success" size="small">全文</el-tag>
          <el-tag v-else type="primary" size="small">摘要</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="任务状态">
          <el-tag v-if="detailData.status === 'completed'" type="success">已完成</el-tag>
          <el-tag v-else-if="detailData.status === 'running'" type="primary">运行中</el-tag>
          <el-tag v-else-if="detailData.status === 'failed'" type="danger">失败</el-tag>
          <el-tag v-else>{{ detailData.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="当前步骤">{{ detailData.currentStep || '-' }}</el-descriptions-item>
        <el-descriptions-item label="总进度">{{ detailData.totalProgress }}%</el-descriptions-item>
        <el-descriptions-item label="优先级">{{ detailData.priority }}</el-descriptions-item>
        <el-descriptions-item label="重试次数">{{ detailData.retryCount }} / {{ detailData.maxRetry }}</el-descriptions-item>
        <el-descriptions-item label="工作线程">{{ detailData.workerThread || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="开始时间" :span="2">{{ detailData.startedAt || '-' }}</el-descriptions-item>
        <el-descriptions-item label="完成时间" :span="2">{{ detailData.completedAt || '-' }}</el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2">
          <span style="color: red;">{{ detailData.errorMessage || '-' }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider>任务步骤</el-divider>
      
      <el-steps :active="getActiveStep()" finish-status="success" align-center>
        <el-step title="文本清理" :description="getStepDesc('clean_data')"></el-step>
        <el-step title="AI翻译" :description="getStepDesc('ai_translate')"></el-step>
        <el-step title="内容保存" :description="getStepDesc('save_content')"></el-step>
        <el-step title="中文TTS" :description="getStepDesc('tts_generate_cn')"></el-step>
        <el-step title="英文TTS" :description="getStepDesc('tts_generate_en')"></el-step>
      </el-steps>

      <el-table :data="detailData.steps" style="margin-top: 20px;" border>
        <el-table-column label="步骤名称" prop="stepName" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.stepName === 'clean_data'">文本清理</span>
            <span v-else-if="scope.row.stepName === 'ai_translate'">AI翻译</span>
            <span v-else-if="scope.row.stepName === 'save_content'">内容保存</span>
            <span v-else-if="scope.row.stepName === 'tts_generate_cn'">中文TTS</span>
            <span v-else-if="scope.row.stepName === 'tts_generate_en'">英文TTS</span>
            <span v-else-if="scope.row.stepName.startsWith('ai_translate_chunk_')">AI翻译块{{ scope.row.stepName.split('_')[3] }}</span>
            <span v-else-if="scope.row.stepName.startsWith('tts_sentence_')">TTS句子{{ scope.row.stepName.split('_')[3] }}</span>
            <span v-else>{{ scope.row.stepName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 'completed'" type="success">已完成</el-tag>
            <el-tag v-else-if="scope.row.status === 'running'" type="primary">运行中</el-tag>
            <el-tag v-else-if="scope.row.status === 'failed'" type="danger">失败</el-tag>
            <el-tag v-else type="info">待处理</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="进度" prop="progress" width="80">
          <template slot-scope="scope">{{ scope.row.progress }}%</template>
        </el-table-column>
        <el-table-column label="开始时间" prop="startedAt" width="160" />
        <el-table-column label="完成时间" prop="completedAt" width="160" />
        <el-table-column label="错误信息" prop="errorMessage" :show-overflow-tooltip="true" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listTaskQueue, getTaskQueue, submitTask, pauseTask, resumeTask, cancelTask, retryTask, delTaskQueue } from "@/api/tzai/taskQueue";

export default {
  name: "TaskQueue",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务队列表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 详情数据
      detailData: {},
      // 进度条颜色
      customColors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        articleId: null,
        status: null,
        currentStep: null
      },
      // 表单参数
      form: {
        articleId: null,
        priority: 0,
        aiModelIds: [],
        aiParallelLevel: 5,
        ttsEngineId: 1,
        ttsParallelLevel: 5,
        cnVoice: 'xiaoyun',
        enVoice: 'jenny'
      },
      // 表单校验
      rules: {
        articleId: [
          { required: true, message: "文章ID不能为空", trigger: "blur" }
        ],
        ttsEngineId: [
          { required: true, message: "TTS引擎不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    // 定时刷新（每10秒）
    this.timer = setInterval(() => {
      this.getList();
    }, 10000);
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    /** 查询任务队列列表 */
    getList() {
      this.loading = true;
      listTaskQueue(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: null,
        priority: 0,
        aiModelIds: [],
        aiParallelLevel: 5,
        ttsEngineId: 1,
        ttsParallelLevel: 5,
        cnVoice: 'xiaoyun',
        enVoice: 'jenny'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const config = {
            ai_model_ids: this.form.aiModelIds,
            ai_parallel_level: this.form.aiParallelLevel,
            tts_engine_id: this.form.ttsEngineId,
            tts_parallel_level: this.form.ttsParallelLevel,
            voice_config: {
              cn_voice: this.form.cnVoice,
              en_voice: this.form.enVoice
            }
          };
          
          const data = {
            articleId: this.form.articleId,
            priority: this.form.priority,
            config: JSON.stringify(config)
          };
          
          submitTask(data).then(response => {
            this.$modal.msgSuccess("任务创建成功，已开始执行");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 查看详情 */
    handleDetail(row) {
      getTaskQueue(row.taskId).then(response => {
        this.detailData = response.data;
        // 🔥 从params中提取steps数据
        if (this.detailData.params && this.detailData.params.steps) {
          this.detailData.steps = this.detailData.params.steps;
        } else {
          this.detailData.steps = [];
        }
        this.detailOpen = true;
      });
    },
    /** 启动任务 */
    handleStart(row) {
      this.$modal.confirm('是否确认启动任务ID为"' + row.taskId + '"的任务?').then(() => {
        return resumeTask(row.taskId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("启动成功");
      }).catch(() => {});
    },
    /** 暂停任务 */
    handlePause(row) {
      this.$modal.confirm('是否确认暂停任务ID为"' + row.taskId + '"的任务?').then(() => {
        return pauseTask(row.taskId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("暂停成功");
      }).catch(() => {});
    },
    /** 继续任务 */
    handleResume(row) {
      this.$modal.confirm('是否确认继续任务ID为"' + row.taskId + '"的任务?').then(() => {
        return resumeTask(row.taskId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("继续成功");
      }).catch(() => {});
    },
    /** 取消任务 */
    handleCancel(row) {
      this.$modal.confirm('是否确认取消任务ID为"' + row.taskId + '"的任务?').then(() => {
        return cancelTask(row.taskId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消成功");
      }).catch(() => {});
    },
    /** 重试任务 */
    handleRetry(row) {
      this.$modal.confirm('是否确认重试任务ID为"' + row.taskId + '"的任务?').then(() => {
        return retryTask(row.taskId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("重试成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids;
      this.$modal.confirm('是否确认删除任务ID为"' + taskIds + '"的数据项？').then(() => {
        return delTaskQueue(taskIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 获取激活步骤 */
    getActiveStep() {
      const stepMap = {
        'clean_data': 0,
        'ai_translate': 1,
        'save_content': 2,
        'tts_generate_cn': 3,
        'tts_generate_en': 4
      };
      return stepMap[this.detailData.currentStep] || 0;
    },
    /** 获取步骤描述 */
    getStepDesc(stepName) {
      if (!this.detailData.steps) return '';
      const step = this.detailData.steps.find(s => s.stepName === stepName);
      if (!step) return '未开始';
      if (step.status === 'completed') return '已完成';
      if (step.status === 'running') return '进行中';
      if (step.status === 'failed') return '失败';
      return '待处理';
    },
    /** 获取处理模式 */
    getProcessMode(task) {
      if (!task || !task.config) return 'summary';
      try {
        const config = JSON.parse(task.config);
        return config.processMode || 'summary';
      } catch (e) {
        return 'summary';
      }
    }
  }
};
</script>

